package com.gin.no_gay_alliance.fragment.main;

import android.content.DialogInterface;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.gin.nga.exception.NgaException;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.databinding.FragmentMainNoticeBinding;
import com.gin.no_gay_alliance.enums.MessageWhat;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.fragment.notice.MessageNoticeFragment;
import com.gin.no_gay_alliance.fragment.notice.RecommendNoticeFragment;
import com.gin.no_gay_alliance.fragment.notice.ReplyNoticeFragment;
import com.gin.no_gay_alliance.manager.NoticeManager;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.viewmodel.notice.BaseNoticeModel;
import com.gin.no_gay_alliance.viewmodel.notice.NoticeDataModel;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.Locale;

/**
 * 提醒消息
 */
public class MainNoticeFragment extends BaseBindingFragment<FragmentMainNoticeBinding> implements TabLayoutMediator.TabConfigurationStrategy {
    private static final String TAG = MainNoticeFragment.class.getSimpleName();
    private NoticeDataModel noticeData;
    private ReplyNoticeFragment replyNoticeFragment;
    private MessageNoticeFragment messageNoticeFragment;
    private RecommendNoticeFragment recommendNoticeFragment;
    private TabLayoutMediator tabLayoutMediator;

    /**
     * onCreateView 的后续操作
     */
    @Override
    protected void onCreateView() {
        NoticeManager noticeManager = MyApplication.app.managerFactory.getNoticeManager();
        this.noticeData = noticeManager.getNoticeData();
        b.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                switch (position) {
                    case 0:
                        replyNoticeFragment = new ReplyNoticeFragment();
                        replyNoticeFragment.setData(noticeData.replyNotices);
                        return replyNoticeFragment;
                    case 1:
                        messageNoticeFragment = new MessageNoticeFragment();
                        messageNoticeFragment.setData(noticeData.msgNotices);
                        return messageNoticeFragment;
                    case 2:
                        recommendNoticeFragment = new RecommendNoticeFragment();
                        recommendNoticeFragment.setData(noticeData.recommendNotices);
                        return recommendNoticeFragment;
                    default:
                        throw new RuntimeException("没有那个标签");
                }
            }

            @Override
            public int getItemCount() {
                return 3;
            }
        });

        attachTabLayout();
    }

    /**
     * 处理消息
     *
     * @param message 消息
     * @return 是否消耗
     */
    @Override
    public boolean handleMessage(@NonNull Message message) {
        // 消息已读
        if (message.what == MessageWhat.ON_READ_NOTICE.ordinal()) {
            Log.d(TAG, "handleMessage: " + "消息已读");
            save();
            attachTabLayout();
            return true;
        }

        return super.handleMessage(message);
    }

    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        switch (position) {
            case 0:
                long c0 = BaseNoticeModel.countUnread(noticeData.replyNotices);
                if (c0 > 0) {
                    tab.setText(String.format(Locale.CHINA, "回复(%d)", c0));
                } else {
                    tab.setText("回复");
                }
                break;
            case 1:
                long c1 = BaseNoticeModel.countUnread(noticeData.msgNotices);
                if (c1 > 0) {
                    tab.setText(String.format(Locale.CHINA, "私信(%d)", c1));
                } else {
                    tab.setText("私信");
                }
                break;
            case 2:
                long c2 = BaseNoticeModel.countUnread(noticeData.recommendNotices);
                if (c2 > 0) {
                    tab.setText(String.format(Locale.CHINA, "赞踩(%d)", c2));
                } else {
                    tab.setText("赞踩");
                }
                break;
            default:
                throw new RuntimeException("没有那个标签");
        }
    }

    /**
     * 加载菜单
     *
     * @param menu     菜单
     * @param inflater 渲染器
     */
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.refresh_menu, menu);
        inflater.inflate(R.menu.notice_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.read_all) {
            noticeData.readAll();
            save();
            updateData();
            return true;
        }
        if (item.getItemId() == R.id.menu_item_refresh) {
            toast("正在刷新...");
            MyApplication.app.managerFactory.getNoticeManager().updateData(new Callback<NoticeDataModel>() {
                @Override
                public void onSuccess(NoticeDataModel data) {
                    noticeData = data;
                    ui(MainNoticeFragment.this::updateData);
                    toast("已刷新");
                }

                @Override
                public void handleException(NgaException e) {
                    Callback.super.handleException(e);
                    toast("已刷新");
                }
            });
            return true;
        }
        if (item.getItemId() == R.id.delete) {


            // 清空消息
            AlertDialogUtils.showConfirm(requireContext(), "清空消息", "即将清空所有提醒消息, 本操作不可逆", (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    MyApplication.app.managerFactory.getNoticeManager().clear(data -> {
                        toast(data);
                        ui(this::updateData);
                    });
                }
            });
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 保存当前数据
     */
    public void save() {
        MyApplication.app.managerFactory.getNoticeManager().save(noticeData);
    }

    @Override
    public void onResume() {
        super.onResume();
        updateData();
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        menu.findItem(R.id.delete).setVisible(noticeData != null && noticeData.count() > 0);
        menu.findItem(R.id.read_all).setVisible(noticeData != null && noticeData.countUnread() > 0);
        super.onPrepareOptionsMenu(menu);
    }

    /**
     * 关联
     */
    private void attachTabLayout() {
        tabLayoutMediator = attachTabLayout(tabLayoutMediator, b.tabLayout, b.vp2);
    }

    /**
     * 更新数据
     */
    private void updateData() {

        // 从管理器中获取最新数据
        // 重新计算未读数量
        attachTabLayout();
        // 更新子Fragment的数据
        if (replyNoticeFragment != null) {
            replyNoticeFragment.setData(noticeData.replyNotices);
        }
        if (messageNoticeFragment != null) {
            messageNoticeFragment.setData(noticeData.msgNotices);
        }
        if (recommendNoticeFragment != null) {
            recommendNoticeFragment.setData(noticeData.recommendNotices);
        }
        // 更新菜单状态
        requireActivity().invalidateOptionsMenu();
    }
}